<template>
  <div class="app-container">
    <el-table :data="tableData" border style="width: 100%" v-loading="loading" show-summary
      :summary-method="calculateSummary" :span-method="objectSpanMethod" :cell-class-name="tableRowClassName">
      <el-table-column prop="revenueName" label="项目" width="120" align="center" />
      <el-table-column prop="year" label="时间" width="120" align="center" />
      <!-- <el-table-column label="差值" width="120" align="center" />
      <el-table-column label="上次统计时间" align="center">
        <el-table-column label="XX年X月X日" width="120" align="center" />
      </el-table-column>
      <el-table-column label="本次统计时间" align="center">
        <el-table-column label="XX年X月X日" width="120" align="center" />
      </el-table-column> -->
      <el-table-column prop="totalValue" label="总产值" align="center">
        <el-table-column prop="totalValue.uploaded" label="已上传" width="120" align="center" />
        <el-table-column prop="totalValue.toBeUploaded" label="待上传" width="120" align="center" />
        <el-table-column prop="totalValue.inReview" label="正审核" width="120" align="center" />
        <el-table-column prop="totalValue.unaudited" label="未审核" width="120" align="center" />
      </el-table-column>

      <el-table-column v-for="item in paymentDeptList" :prop="item.field" :label="item.paymentDeptName" align="center">
        <el-table-column :prop="`${item.field}.uploaded`" label="已上传" width="120" align="center" />
        <el-table-column :prop="`${item.field}.toBeUploaded`" label="待上传" width="120" align="center" />
        <el-table-column :prop="`${item.field}.inReview`" label="正审核" width="120" align="center" />
        <el-table-column :prop="`${item.field}.unaudited`" label="未审核" width="120" align="center" />
      </el-table-column>

      <el-table-column label="合计" width="120" align="center" :formatter="formatterSum" />

    </el-table>
  </div>
</template>

<script setup lang="js">
import { ref } from 'vue';
import { getPaymentdept, getSettlementProgress } from '@/api/statement';
import { pinyin } from "pinyin-pro";

const { proxy } = getCurrentInstance()
const loading = ref(true)

// 获取当年的一月
const now = new Date();
const year = ref(now.getFullYear())
const historyYear = ref(year.value - 1)

const queryParams = ref({
  settlementDate: year.value,
  endDate: historyYear.value
})

const tableData = ref([
])
const paymentDeptList = ref([

])

const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

//计算行合计
const formatterSum = (row, column, cellValue, index) => {
  cellValue = row.totalValue.uploaded + row.totalValue.toBeUploaded + row.totalValue.inReview + row.totalValue.unaudited
  return cellValue
}

// 尾行合计
const calculateSummary = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    // 第一列不合计
    if (index === 0) {
      sums[index] = '合计';
      return;
    } else if (index === 1) {
      sums[index] = '';
      return;
    } else if (index === columns.length - 1) {
      sums[index] = '合计'
      return;
    }
    const field = (column.property).split(".")
    const values = []

    data.forEach(item => {
      values.push(item[field[0]][field[1]])
    });
    sums[index] = values.reduce((prev, curr) => prev + (parseInt(curr) || 0), 0);


  });
  return sums;
};

// 合并单元格
const objectSpanMethod = ({ row, column, rowIndex, columnIndex, }) => {
  if (columnIndex === 0) {
    if (rowIndex % 2 === 0) {
      return {
        rowspan: 2,
        colspan: 1,
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      }
    }
  }
}

//获取表格数据
const getList = () => {
  loading.value = true;
  getPaymentdept({pageSize: 1000}).then(res => {
    paymentDeptList.value = transformPAYname(res.rows)
  })
  getSettlementProgress(queryParams.value).then(res => {
    tableData.value = processData(res.data)
    loading.value = false;
  })

}

// 转换数据格式
const processData = (data) => {
  const conversionData = Object.values(data.reduce((acc, obj) => {
    const revenueName = obj.revenueName
    const redgerType = pinyin(obj.revenueName, { pattern: 'first', toneType: 'string', separator: '' }) + obj.year
    const year = obj.year;
    const paymentName = pinyin(obj.paymentDeptName, { pattern: 'first', toneType: 'string', separator: '' })
    if (!acc[redgerType]) {
      acc[redgerType] = {
        revenueName: revenueName,
        redgerType: redgerType,
        year: year,
        totalValue: {
          uploaded: 0,
          toBeUploaded: 0,
          inReview: 0,
          unaudited: 0
        }
      };
    }
    if (!acc[redgerType][paymentName]) {
      acc[redgerType][paymentName] = {};
    }
    //插入具体值
    acc[redgerType][paymentName].uploaded = obj.uploaded;
    acc[redgerType][paymentName].toBeUploaded = obj.toBeUploaded;
    acc[redgerType][paymentName].inReview = obj.inReview;
    acc[redgerType][paymentName].unaudited = obj.unaudited;

    return acc;
  }, {}));

  // 计算最后一列合计值
  Object.values(conversionData).forEach(item => {
    let totalValue = {
      uploaded: 0,
      toBeUploaded: 0,
      inReview: 0,
      unaudited: 0
    };
    Object.values(item).forEach(subItem => {
      totalValue.uploaded += parseInt(subItem.uploaded) || 0;
      totalValue.toBeUploaded += parseInt(subItem.toBeUploaded) || 0;
      totalValue.inReview += parseInt(subItem.inReview) || 0;
      totalValue.unaudited += parseInt(subItem.unaudited) || 0;
    });
    item.totalValue = totalValue;
  });
  return conversionData
}

// 把付款单位的名称转成拼音
const transformPAYname = (data) => {
  return data.map(item => {
    const pinyinName = pinyin(item.paymentDeptName, { pattern: 'first', toneType: 'string', separator: '' });
    return {
      paymentDeptName: item.paymentDeptName,
      field: pinyinName
    };
  });
}

//查询列表
const handleQuery = () => {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

//指定列颜色
const tableRowClassName = ({ row, rowIndex, columnIndex }) => {
  const adjustedIndex = columnIndex - 2;
  const colorIndex = Math.floor(adjustedIndex / 4) % 4;

  switch (colorIndex) {
    case 0:
      return 'blue-row';
    case 1:
      return 'purple-row';
    case 2:
      return 'blue-row';
    case 3:
      return 'purple-row';
    default:
      return 'default';
  }
};

getList()
</script>
<style >
.blue-row
{
  background-color: rgb(185, 216, 252) !important;
}

.purple-row
{
  background-color: rgb(222, 185, 252) !important;
}
</style>